# -*- encoding: utf-8 -*-
# k2000-r7 parser
# like http://mail1.kongsberg.kommune.no/k2000-r7/k2post.sett_nsf/frmShowMailBySpecifiedDate?OpenForm&Date=20070801
############################################################################
#    Copyright (C) 2007 by Håvard Gulldahl                                 #
#    havard@gulldahl.no                                                    #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import logging
from datetime import datetime
from time import strptime
import jeje.parser
#import jeje
import re

class parser(jeje.parser.ejeje_parser):
    def parse_enkeltjournal(self, suppe, uri):
        #jeje.parser.ejeje_parser.__init__(self, suppe, postjournal_samling)
        logging.info('starter k2000-r7-parser')

        #self.sett_info(suppe.)
        logging.debug('finner tittelposter i suppa')
        _tittelposter = suppe.findAll('tr', {'bgcolor':'#E1E1E1'})
        logging.debug('fant %d titler', len(_tittelposter))
        for i, tp in enumerate(_tittelposter):
            logging.debug('arbeider med post #%d: %s', i, tp.a.string)
            post = self.legg_til_post()
            post.sett_tittel(unicode(tp.a.string))
            post.sett_offentlig(-1 != tp.a.find('/k2000/k2post.sett_nsf/viewAttachmentsMail'))
            post.sett_uri(self.absoluttifiser(unicode(tp.a['href']), uri))
            rad1 = tp.findNextSibling()
            if rad1.td.string is not None:
                post.sett_kommentar(unicode(rad1.td.string))
            rad2 = rad1.findNextSibling()
            _tittel2 = rad2.b.next.next
            rad3 = rad2.findNextSibling() ## rad3 == skillelinje?
            rad4 = rad3.findNextSibling()
            _arkivsaksnr, refnr = [ x.next.next for x in rad4.findAll('b') ]
            __arkivsaksnr = str(_arkivsaksnr).replace('&nbsp;','')
            _tomrom = __arkivsaksnr.find(' ')
            ___arkivsaksnr, _retning = __arkivsaksnr[0:_tomrom], __arkivsaksnr[_tomrom+1:]
            arkivsaksnr, dokumentnr = _arkivsaksnr.split('-')
            post.sett_retning(_retning[0].upper())
            logging.debug('arkivsaksnr: %s, refnr: %s', arkivsaksnr, refnr)
            post.sett_arkivsaksnr(unicode(arkivsaksnr))
            post.sett_refnr(unicode(refnr))
            post.sett_dokumentnr(unicode(dokumentnr))
            rad5 = rad4.findNextSibling()
            try:
                assert rad5.b.string.lower().strip() == 'fra/til:'
                post.sett_adressat(unicode(rad5.b.next.next))
                rad6 = rad5.findNextSibling()
            except AssertionError:
                logging.debug('Linjen med avsender/mottaker mangler, går rett videre')
                rad6 = rad5
            assert rad6.b.string.lower().strip() == 'saksbehandler:'
            _beh_navn, _beh_org = rad6.b.next.next.split(' (')
            person = post.sett_saksbehandler(unicode(_beh_navn))
            avdeling = person.sett_organisasjon(unicode(_beh_org[:-1]))
            avdeling.type = u'avdeling'
            avdeling.moder_id = post.postjournal.organisasjon_id
            rad7 = rad6.findNextSibling()
            assert rad7.b.string.lower().strip() == 'datert:'
            post.sett_dokumentdato(datetime(*strptime(rad7.b.next.next.strip(), '%d.%m.%Y')[0:6]))
            _lovref = rad7.find(text=re.compile('Unntatt'))
            if _lovref is not None:
                post.sett_lovreferanse(unicode(_lovref))
            post.kontroller_felter()
        return self.journalposter
